import { ElMessage } from 'element-plus'
export interface DownloadParams {
  downloadName: string
  url: string
}

export interface FileInputParams {
  accept: string
}
export const download = (data: DownloadParams) => {
  const aTag = document.createElement('a')
  aTag.setAttribute('href', data.url)
  aTag.setAttribute('download', data.downloadName)
  aTag.click()
  aTag.remove()
  ElMessage.success('正在下载中,请稍后...')
}

export const addFileInput = (params: FileInputParams = { accept: 'application/JSON' }) => {
  const { accept } = params
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = accept
  document.body.appendChild(input)
  input.style.display = 'none'
  return input as HTMLInputElement
}

export const readFile = (e: any) =>
  new Promise((resolve) => {
    const reader: any = new FileReader()
    reader.onload = (event: any) => {
      resolve(JSON.parse(event.target.result))
    }
    reader.readAsText(e.target.files[0])
  })
